package control;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.*;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 * @author Marvin
 * 
* TODO To change the template for this generated type comment go to Window -
 * Preferences - Java - Code Style - Code Templates
 */
public class UploadController extends HttpServlet {

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse res) {
        try {
            SessionFactory sessionFactory = SchoolContentManager.sessionFactory;
            Session session = sessionFactory.getCurrentSession(); //get the session from the sessionFactory
            Transaction transaction = session.beginTransaction(); //start the transaction
            HttpSession sessie = request.getSession();
            UploadedFile file = null;
            System.out.println("nullpointer" + sessie.getAttribute("uploadPage"));
            FileUpload fup = new FileUpload();
            boolean isMultipart = FileUpload.isMultipartContent(request);

// Create a new file upload handler
            System.out.println("isMultipart: " + isMultipart);
            DiskFileUpload upload = new DiskFileUpload();

// Parse the request
            List items = upload.parseRequest(request);

            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                {
                    FileItem item = (FileItem) iter.next();
                    long nano = System.nanoTime();
                    String value = Long.toString(nano);
                    File cfile = new File(item.getName());
                    String filename = value.concat("_").concat(cfile.getName());
                    UploadedFile uploadedFile = null;
                    file = new UploadedFile();
                    if (item.isFormField()) {
                        System.out.println("its a field");
                    } else {
                        System.out.println("its a file");
                        File uploadDirectory = new File(getServletContext().getRealPath("/filedata/"));
                        //File uploadDirectory = new File("http:\\\\145.92.6.83:8080\\filedata\\");
                        File tosave = new File(uploadDirectory, filename);
                        System.out.println("Hier wordt hij bewaard:" + uploadDirectory.getPath());
                        if (!uploadDirectory.exists()) {
                            String strDirectory = uploadDirectory.getPath();
                            boolean createdDir = (new File(strDirectory)).mkdir();
                            if (createdDir) {
                                System.out.println("Directory: " + strDirectory + " created");
                            }
                        } else {
                            System.out.println("Directory: " + uploadDirectory.getName() + " has been found");
                        }
                        item.write(tosave);
                        String getFileSQL = "SELECT * FROM File F WHERE F.fName = '" + item.getName() + "'";
                        ArrayList<UploadedFile> files = (ArrayList) session.createSQLQuery(getFileSQL).list();
                        Iterator it = files.iterator();
                        System.out.println("iterator: " + it.hasNext());
                        //if (!it.hasNext()) {
                        uploadedFile = new UploadedFile();
                        uploadedFile.setfName(item.getName());
                        uploadedFile.setfLocation("http://145.92.6.83:8080/2DEVPDL/filedata/" + filename);
                        uploadedFile.setOwnerName(((Gebruiker)sessie.getAttribute("cuser")).getuCode());
                        uploadedFile.setTeacher((Teacher)session.get(Teacher.class, (String)sessie.getAttribute("user")));
                        uploadedFile.setExercise((Exercise)session.get(Exercise.class,(Integer)sessie.getAttribute("exerciseTitle")));
                        if(sessie.getAttribute("isAnAnswer").equals(true)){
                            uploadedFile.setIsAnswer(true);
                        } else {
                            uploadedFile.setIsAnswer(false);
                        }
                        sessie.setAttribute("createFileError", "<b>File " + uploadedFile.getfName() + " successfully uploaded!</b>");
                        sessie.setAttribute("file", uploadedFile.getfName());
                        sessie.setAttribute("contentPage", "uploadPage.jsp");
                        //addHistory(sessie, "/uploadPage.jsp");
                        //}
                    }
                    if (uploadedFile != null) {
                        session.saveOrUpdate(uploadedFile); //save new file
                    } else {
                        sessie.setAttribute("createFileError", "<b>An unexpected error occured. File not uploaded.");
                    }
                    transaction.commit(); //commit file to data
                }
                res.sendRedirect("index");
            }
        } catch (Exception e) {
            System.out.println("Alert, an error occurred during the upload: " + e);
        }
    }

    private void addHistory(HttpSession sessie, Object attribute) {
        List<Object> historie;
        if (sessie.getAttribute("lastpage") == null) {
            historie = new ArrayList();
        } else {
            historie = (ArrayList<Object>) sessie.getAttribute("lastpage");
        }
        System.out.println("terug naar" + attribute);
        historie.add(attribute);
        sessie.setAttribute("lastpage", historie);
    }
}